// pages/home/addBloodSugar/addBloodSugar.js
const dateTimePicker = require('../../utils/dateTimePicker.js')
var context; //canvas上下文环境
let centerX, centerY, circleR; //大圆圆心半径
const lineWidth = 5; //蓝色环形边框宽度
const pointR = 12; //动画圆圈半径
let top,left,startIndex={x:0,y:0}; //canva距离顶部左边的距离
let canMove = false;
let firstIndex = {}; //仪表盘的初始坐标轴
let defAngle = 0;
let isSave = false;
let nowScrollTop = 0; //距离顶部的距离
let isToImg = false; //canvas是否正在转换成图片，避免多次频闪
const call = require('../../utils/request.js')
const app = getApp();
Page({

  /**
   * 页面的初始数据
   */
  data: {
    winTipType:'', //xt 正常 xtL 低血糖 xtH 高血糖
    winTipShow:false, //显示提示窗口
    showModalStatus:false, //是否显示饮食弹窗
    showModalStatus1:false, //是否显示运动弹窗
    openBz: false, //是否下拉备注
    openYs: false, //是否下拉饮食
    openYd:false,   //是否下拉运动
    vip:app.globalData.vip, //是否vip
    dateTime:null, //日期
    deviceTime: null, //设备测量时间
    dateTimeArray: null, //日期数组
    addType: 0, //手动0  设备1xxxxxxxxxxxxxxxxx
    hasDevice: false, //是否有绑定设备xxxxxxxxxxxxxxxxx
    xtType: 0, //初始化0 正常1 低血糖2 高血糖3
    xtTypeName:['等待设备数据导入','血糖正常','血糖偏低','血糖偏高'],
    xyColor:['#409EFF','#00726D','#FF4D4F'],
    xtClass:['gray','green','blue','red'],
    canvasWidth: 240, //仪表图宽度
    currentElec: 0, //当前糖量 手动录入
    mealsTypeId:1, //当前餐别 手动录入
    currentElec1:0, //当前糖量 设备上传
    mealsTypeId1:1,//当前餐别 设备上传
    currentElecId: null, //糖量ID 设备上传
    food:'', //饮食
    sport: '', //运动
    imgUrl:`${call.host}/home/imgs/icon_`,
    remark:'', //备注
    //备注选项
    remarkObj:[{name:'无不适'},{name:'三多'},{name:'乏力'},{name:'腹痛呕吐'},{name:'头疼'},{name:'昏迷'},{name:'抽搐'},{name:'呼吸快'},{name:'出汗'},{name:'心悸'},{name:'饥饿'}],
    //运动
    sportArr:[],
    foodArr:[],
    mealsType:{}, //餐别选项
    height:{  //身高
      arr:[],
      index:null
    },
    weight:{  //体重
      arr:[],
      index:43
    },
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    this.initData();
    //获取控糖目标值
    this.init();
    //日期选择器处理
    // let date = new Date();
    // let year = date.getFullYear();
    // var obj = dateTimePicker.dateTimePicker(year-10, year+10);
    // let lastArray = obj.dateTimeArray.pop();
    // let lastTime = obj.dateTime.pop();
    // this.setData({
    //   dateTime: obj.dateTime,
    //   dateTimeArray: obj.dateTimeArray,
    // });

    //获取设备上传对应的血糖数据信息
    this.getDeviceEqt();  //xzxxxxxxxxxxxxxxxxxxxxxx
  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {
    
  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {

  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function () {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function () {
    //如果执行过保存的话，返回刷新日统计折线图
    // if(isSave){
    //   let pages = getCurrentPages();
    //   let prePage = pages[pages.length - 2];
    //   prePage.getDayStatistics();
    // }
  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function () {

  },

  /**
   * 页面滚动事件
   */
  onPageScroll: function (e) {
    nowScrollTop = e.scrollTop;
    if(e.scrollTop==0 && isToImg){
      this.imgToCanvas();
    }else if(!isToImg){
      this.canvasToImg();
    }
    
  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function () {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function () {

  },

  /**
   * 初始化部分数据 
   */
  initData(){
    let height = [[],[],[],['cm'],[]],weight=[[],[],[],['kg'],[]],time=[[],[],[],[]],sportTimeArr=[[''],['分钟']];
    //身高范围
    for(let i=30;i<231;i++){
      height[2].push(i)
    }
    //体重范围
    for(let i=17;i<201;i++){
      weight[2].push(i)
    }
    //测糖时间
    let date1 = new Date();
    for(let i=0;i<90;i++){
      let date2 = new Date(date1)
      date2.setDate(new Date(date2.getDate()-i));
      let week = i==0?'今天':this.getWeek(date2.getDay());
      time[1].unshift(`${this.getDbNum(date2.getMonth()+1)}月${this.getDbNum(date2.getDate())}日 ${week}`)
    }
    for(let i=0;i<60;i++){
      if(i<24){
        time[2].push(this.getDbNum(i));
      }
      time[3].push(this.getDbNum(i));
    }
    //运动时间
    for(let i=1;i<37;i++){
      sportTimeArr[0].push(5*i);
    }

    //赋值
    this.setData({
      height:{
        arr:height,
        index:[0,0,135,0,0]
      },
      weight:{
        arr:weight,
        index:[0,0,43,0,0]
      },
      dateTimeArray:time,
      dateTime:[0,89,time[2].indexOf(this.getDbNum(date1.getHours())),time[3].indexOf(this.getDbNum(date1.getMinutes()))],
      sportTimeArr:sportTimeArr,
      vip:app.globalData.vip,
    })
  },

  /**
   * 初始化用户配置信息
   */
  init(){
    wx.showLoading({
      title: '获取控糖目标值',
      mask:true
    })
    call.post('/api/index/meals_time').then(res=>{
      console.log("获取用户基本配置信息",res)
      let mealsType = {};
      const data = res.data.data.mealsconf;
      for(let i of data){
        if(i.meals == 1){
          mealsType = Object.assign(mealsType,{
            1:{
              name:'早餐前',
              sugar:[i.before_low,i.before_high],
              time:i.start_time
            },
            2:{
              name:'早餐后',
              sugar:[i.after_low,i.after_high],
              time:i.end_time
            }
          })
        }else if(i.meals == 2){
          mealsType = Object.assign(mealsType,{
            3:{
              name:'午餐前',
              sugar:[i.before_low,i.before_high],
              time:i.start_time
            },
            4:{
              name:'午餐后',
              sugar:[i.after_low,i.after_high],
              time:i.end_time
            }
          })
        }else if(i.meals == 3){
          mealsType = Object.assign(mealsType,{
            5:{
              name:'晚餐前',
              sugar:[i.before_low,i.before_high],
              time:i.start_time
            },
            6:{
              name:'晚餐后',
              sugar:[i.after_low,i.after_high],
              time:i.end_time
            }
          })
        }else if(i.meals == 4){
          mealsType = Object.assign(mealsType,{
            7:{
              name:'睡前',
              sugar:[i.before_low,i.before_high],
              time:i.start_time
            }
          })
        }
      }
      const basic = res.data.data.basic[0];
      
      this.setData({
        mealsType:mealsType,
        [`height.index`]: [0,0,this.data.height.arr[2].indexOf(basic.height)||135,0,0],
        [`weight.index`]: [0,0,this.data.weight.arr[2].indexOf(parseInt(basic.weight))||43,0,0],
      })
      wx.hideLoading();
      this.createCanvas();
      this.changeDateTime({detail:{value:this.data.dateTime}}); //实例化餐别
    })
  },

  /**
   * 获取设备上传对应的血糖数据
   */
  getDeviceEqt(){
    wx.showLoading({
      title: '正在获取数据',
      mask:true
    })
    call.post('/api/index/decive_data').then(res=>{
      wx.hideLoading();
      console.log("设备上传的血糖值",res)
      const data = res.data.data;
      if(data.is_bundled == 0){
        this.setData({
          hasDevice: false
        })
      }else{
        if(data.data){
          this.setData({
            hasDevice: (data.is_bundled==1?true:false),
            deviceTime:data.data.test_at,
            currentElec1:data.data.glu,
            currentElecId:data.data.id,
            mealsTypeId1:data.data.meals,
            xtType: data.data.state,
          })
        }else{
          this.setData({
            hasDevice: (data.is_bundled==1?true:false),
          })
        }
      }
    })
  },

  /**
   * 时间取中间值,用来获取具体的测糖时间,type 0开始时间，1结束时间
   */
  getSugarTime(time,type){
    if(type==0){
      return time%1==0?time+':01':parseInt(time)+':31';
    }else{
      return time%1==0?time+':00':parseInt(time)+':30';
    }
  },

  /**
   * 删除运动
   */
  delSport(e){
    const index = e.currentTarget.dataset.index;
    let arr = this.data.sportArr;
    arr.splice(index,1);
    this.setData({sportArr:arr});
  },
  /**
   * 删除饮食 
   */
  delFood(e){
    const index = e.currentTarget.dataset.index;
    let arr = this.data.foodArr;
    arr.splice(index,1);
    this.setData({foodArr:arr});
  },

  /**
   * input数据绑定
   */
  bindInput(e){
    const name = e.currentTarget.dataset.name;
    this.setData({
      [`${name}`]:e.detail.value
    })
  },

   /**
   * 日期选择
   */
  changeDateTime(e) {
    const date = e.detail.value;
    const mealsType = this.data.mealsType;
    let time = date.slice(2,4).join(':');
    this.setData({ dateTime: date});
    let key = null;
    for(let i in mealsType){
      let y = i==7?1:parseInt(i)+1;
      // if(this.hourCompare(time , mealsType[i].time) && this.hourCompare(mealsType[y].time,time)){
      if(this.hourCompare(time,mealsType[i].time,mealsType[y].time)){ 
        this.getTimeInt(time,mealsType[i].time,mealsType[y].time,i,y)
      }
    }
  },

  /**
   * 运动时间选择
   */
  changeSportTime(e){
    const index = e.currentTarget.dataset.index;
    this.setData({
      [`sportArr[${index}].time`]:e.detail.value
    })
  },

  /**
   * 保持日期是两位数
   */

 /**
  * 时间判断大小 time1 < time < time2
  */
  hourCompare(time,time1,time2){
    let date1 = '2020/08/18',date2 = '2020/08/19'; //默认日期，便于获取时间戳
    let t = new Date(date1+' '+time).getTime();
    let t1 = new Date(date1+' '+time1).getTime();
    let t2 = new Date(date1+' '+time2).getTime();
    if(t1>t2){ //相差天
      t2 = new Date(date2+' '+time2).getTime();
      if(t1>t){
        t = new Date(date2+' '+time).getTime();
      }
    }
    return (t1<=t && t<=t2);
  },
   /**
   *  比较更接近的时间 对应选择餐别
   */
  getTimeInt(time,time1,time2,time1Type,time2Type){
    let date1 = '2020/08/18',date2 = '2020/08/19'; //默认日期，便于获取时间戳
    let t = new Date(date1+' '+time).getTime();
    let t1 = new Date(date1+' '+time1).getTime();
    let t2 = new Date(date1+' '+time2).getTime();

    let type = Math.abs(t-t1)>Math.abs(t-t2)?time2Type:time1Type;
    if(t1>t2){ //相差天
      type = 7;
      // t2 = new Date(date2+' '+time2).getTime();
      if(t1>t){
        // t = new Date(date2+' '+time).getTime();
        type = 1;
      }
    }
    

    this.setData({
      mealsTypeId:type
    })
    this.startAnimate();
  },

  /**
   * 餐别选择 
   */
  chooseMealsType(e){
    const type= e.currentTarget.dataset.type;
    this.setData({
      mealsTypeId:type
    })
    this.startAnimate(); //刷新canvas，血糖偏值颜色显示
  },

  /**
   * 备注多选
   */
  chooseRemark(e){
    const index = e.currentTarget.dataset.index;
    let checked = this.data.remarkObj[index].checked;
    checked = checked?!checked:true;
    this.setData({
      [`remarkObj[${index}].checked`]: checked
    })
  },

  /**
   * 下拉选择事件
   */
  bindPickerChange(e){
    let field = e.currentTarget.dataset.name;
    const type = e.currentTarget.dataset.type;
    this.setData({
      [`${field}.index`]:e.detail.value
    })

    let value = this.data[field].arr[2][e.detail.value[2]];
    if(field == 'weight'){
      value = this.data[field].arr[2][e.detail.value[2]];
    }else if(field == "height"){
      value = this.data[field].arr[2][e.detail.value[2]];
    }

    this.modifyInfo(field,value,type);
  },

   /**
   * 修改个人信息
   */
  modifyInfo(field,value,type){
    wx.showLoading({
      title: '正在保存',
      mask:true
    })
    console.log(field,value,type)
    call.post('/api/home/update_field',{
      field,value,type
    }).then(res=>{
      console.log("修改个人信息",res)
      wx.hideLoading();
    })
  },
  
  /**
   * 保存血糖信息 
   */
  save(){
    const addType = this.data.addType;
    //判断是否有血糖值
    if((addType==0&&this.data.currentElec == 0) || (addType==1&&!this.data.currentElecId)){
      wx.showToast({
        title: '请录入血糖',
        icon:'none'
      })
      return;
    }

    let url = '/api/index/add_glu';
    let data = {};
    let xtType = 1; //血糖是否正常/高/低

    //获取备注
    const remarkObj = this.data.remarkObj;
    let remark = '';
    for(let i of remarkObj){
      if(i.checked) remark+=(i.name+',');
    }
    if(this.data.remark.trim().length == 0){
      remark = remark.substring(0,remark.length-1);
    }else{
      remark += this.data.remark;
    }
    //获取运动
    let sport = '';
    const sportArr = this.data.sportArr;
    for(let i of sportArr){
      sport+=`${i.name}${i.time}分钟,`
    }
    if(sport.length>0) sport = sport.substring(0,sport.length-1);
    //获取饮食
    let food = '';
    const foodArr = this.data.foodArr;
    for(let i of foodArr){
      food += `${i.name},`
    }
    if(food.length>0) food = food.substring(0,food.length-1);

    //判断是否手动录入 还是 设备上传
    if(addType == 0){
      //获取时间
      const dateTimeArray = this.data.dateTimeArray;
      const dateTime = this.data.dateTime;
      const nowDate = new Date();
      const month = dateTimeArray[1][dateTime[1]].split('月');
      const day = month[1].split('日')[0];
      let time = `${nowDate.getFullYear()}-${month[0]}-${day} ${dateTimeArray[2][dateTime[2]]}:${dateTimeArray[3][dateTime[3]]}`;
      const currentElec = parseFloat(this.data.currentElec)
      const minNum = parseFloat(this.data.mealsType[this.data.mealsTypeId].sugar[0])
      const maxNum = parseFloat(this.data.mealsType[this.data.mealsTypeId].sugar[1])
      let state = 1;
      if(currentElec<minNum) state=2;
      else if(currentElec>maxNum) state=3;
      xtType = state; //血糖是否正常

      data = {
        glu: currentElec, //血糖值
        device_code: '', //设备编码
        meals: this.data.mealsTypeId,  //餐别
        diet: food, //饮食
        sport: sport,  //运动
        remark: remark, //备注
        type:(addType+1), //1手动录入 2自动录入
        test_at: time, //测试时间
        state:state //1正常 2偏低 3偏高
      }
    }else{
      if(this.data.currentElecId){
        xtType = this.data.xtType;
        url = '/api/index/device_update';
        data = {
          id: this.data.currentElecId,
          diet: food, //饮食
          sport: sport,  //运动
          remark: remark, //备注
        }
      }else{
        wx.showToast({
          title: '请录入血糖',
          icon:'none'
        })
        return;
      }
    }
    
    console.log(xtType)
    isSave = true;
    wx.showLoading({
      title: '正在保存',
      mask: true
    })
    call.post(url,data).then(res=>{
      console.log("保存血糖信息",res)
      wx.hideLoading();
      if(res.statusCode == 200 && res.data.code == 0){
        wx.showToast({
          title: '保存成功',
        })
        let timer = setTimeout(()=>{
          this.setData({
            winTipShow:true,
            winTipType:(xtType==1?'xt':xtType==2?'xtL':'xtH')
          })
          clearTimeout(timer)
        },1500)
      }
    })
  },

  //保存成功后确定提示
  winTipSure(){
    wx.navigateBack({
      delta: 1,
    })
  },

  //canvas替换成图片
  canvasToImg(){
    isToImg = true;
    if(!this.data.radarImg){
      wx.canvasToTempFilePath({
        x: 0,
        y: 0,
        width: this.data.canvasWidth,
        height: this.data.canvasWidth,
        canvasId: 'canvas',
        success: res=> {
          this.setData({ radarImg: res.tempFilePath});
        }
      });
    }
  },
  //图片替换成canvas
  imgToCanvas(e){
    isToImg = false;
    if(this.data.radarImg && nowScrollTop < 5){
      this.setData({radarImg:null});
      this.startAnimate();
    }
  },

  /**
   * 录入方式
   */
  chooseType(e){
    const type = e.currentTarget.dataset.type;
    this.setData({
      addType: type
    })
  },

  /**
   * 血糖录入
   */
  chooseXt(e){
    const type = e.currentTarget.dataset.type;
    let currentElec = parseFloat(this.data.currentElec);
    if(type == "del"){
      if(currentElec==0) return;
      currentElec = (currentElec-0.1).toFixed(1);
    }else if(type == "add"){
      if(currentElec==35) return;
      currentElec = (currentElec+0.1).toFixed(1);
    }
    this.setData({
      currentElec
    })
    
    this.startAnimate();
  },

  /**
   * 页面跳转 设备绑定
   */
  toUrl(e){
    const type = e.currentTarget.dataset.type;
    const url = e.currentTarget.dataset.url;
    if(type == "tabbar"){
      wx.switchTab({
        url: url,
      })
    }else{
      let str = '';
      if(type == 'sport'){
        console.log(this.data.sportArr)
        str=`?arr=${JSON.stringify(this.data.sportArr)}`
      }else if(type == "food"){
        str=`?arr=${JSON.stringify(this.data.foodArr)}`
      }
      wx.navigateTo({
        url: url+str,
      })
    }
  },
  
  // canvas绘制==========================================================
  createCanvas() {
    // 底部主要图形
    context = wx.createCanvasContext('canvas')
    centerX = (this.data.canvasWidth)/2
    centerY = (this.data.canvasWidth)/2
    circleR = centerX-20

    //实例化 初始值为0的点的坐标以及对应正坐标轴的角度差
    firstIndex.x = (circleR-lineWidth/2) * Math.cos(((112.5 - pointR/4))/180 * Math.PI);
    firstIndex.y = (circleR-lineWidth/2) * Math.sin(((112.5 - pointR/4))/180 * Math.PI);
    let defIndex = {x:-100,y:0}; //举例默认，方便计算角度差
    var v1 = (defIndex.x * firstIndex.x) + (defIndex.y * firstIndex.y);
    var pa_val = Math.sqrt(defIndex.x * defIndex.x + defIndex.y * defIndex.y);
    var pb_val = Math.sqrt(firstIndex.x * firstIndex.x + firstIndex.y * firstIndex.y);
    var cosAgl = v1 / (pa_val * pb_val);
    defAngle = Math.acos(cosAgl) * 180 / Math.PI;
    console.log("默认角度差为",defAngle)

    this.startAnimate()
    // timer = setInterval(() => {
    //     this.startAnimate()
    // }, 1000)
  },
  startAnimate() {
    const mealsType = this.data.mealsType;
    const mealsTypeId = this.data.mealsTypeId;
    const minNum = parseFloat(mealsType[mealsTypeId].sugar[0]);
    const maxNum = parseFloat(mealsType[mealsTypeId].sugar[1]);
    const currentElec = parseFloat(this.data.currentElec);
    context.clearRect(0, 0, this.data.canvasWidth, this.data.canvasWidth)
    //数值范围取色
    let color = this.data.xyColor[0];
    if(currentElec>=minNum && currentElec<=maxNum){
      color = this.data.xyColor[1];
    }else if(currentElec>maxNum){
      color = this.data.xyColor[2];
    }
    
    this.drawLightCircle()
    this.drawLineCircle(currentElec, this.data.xyColor,minNum,maxNum)
    this.drawDotted()
    this.drawScale()
    this.drawText(currentElec,color)
    this.drawAnimateCircle(currentElec, this.data.xyColor,minNum,maxNum)
    this.drawAnimateDot(currentElec)

  },
  // 绘制静态大圆
  drawLightCircle() {
    context.save();
    context.setStrokeStyle('#E9E9E9');
    context.setLineWidth(lineWidth);
    context.beginPath();
    context.translate(centerX, centerY);
    context.rotate(112.5 * Math.PI/180);
    context.arc(0, 0, circleR-lineWidth/2, (Math.PI/180)*0, (Math.PI/180)*315, false);
    context.stroke();
    context.closePath();
    context.restore();
  },
  // 绘制虚线
  drawDotted(){
    context.save();
    context.setStrokeStyle('#E9E9E9');
    context.setLineWidth(2);
    context.setLineDash([5,5])
    context.beginPath();
    context.translate(centerX, centerY);
    context.rotate(112.5 * Math.PI/180);
    context.arc(0, 0, circleR-lineWidth/20-12, (Math.PI/180)*0, (Math.PI/180)*315, false);
    context.stroke();
    context.closePath();
    context.restore();
  },
  // 绘制间隔线条
  drawLineCircle(percent,color,minNum,maxNum) {
    let angel = 4.5 //每间隔多少度画一条线
    let outR = circleR + lineWidth   //间条线外边点距离中心点的长度（即外边半径）
    let inR = circleR + lineWidth * 2 + 7 //间条线内边点距离中心点的长度（即内边半径）
    context.save()
    context.translate(centerX, centerY);  //把中心点移动到
    context.rotate(112.5 * Math.PI/180); //旋转画布165弧度
    // 遍历，通过两个半径长度outR和inR，利用三角函数得到两个点的坐标绘制线条
    // 遍历的序列号i即为角度值
    for(var i = 0;i<71;i++){
        // let isF = i%5 == 0;    (isF?inR+5:inR) * Math.cos(angel * i / 180 * Math.PI)
        let startX = outR * Math.cos(angel * i / 180 * Math.PI)
        let startY = outR * Math.sin(angel * i / 180 * Math.PI)
        let endX = inR * Math.cos(angel * i / 180 * Math.PI)
        let endY = inR * Math.sin(angel * i / 180 * Math.PI)
        if(percent<minNum){
          let angel1 = percent/36*328/angel;
          if(i<angel1){
            context.beginPath();
            context.setLineWidth(3);
            context.setStrokeStyle(color[0]);
            context.moveTo(startX, startY)
            context.lineTo(endX, endY)
            context.stroke();
            context.closePath();
          }else{
            context.beginPath();
            context.setLineWidth(3);
            context.setStrokeStyle("#E9E9E9");
            context.moveTo(startX, startY)
            context.lineTo(endX, endY)
            context.stroke();
            context.closePath();
          }
        }else if(percent>=minNum && percent<=maxNum){
          let angel1 = minNum/36*328/angel,angel2 = percent/36*328/angel;
          if(i<angel1){
            context.beginPath();
            context.setLineWidth(3);
            context.setStrokeStyle(color[0]);
            context.moveTo(startX, startY)
            context.lineTo(endX, endY)
            context.stroke();
            context.closePath();
          }else if(i>=angel1 && i<=angel2){
            context.beginPath();
            context.setLineWidth(3);
            context.setStrokeStyle(color[1]);
            context.moveTo(startX, startY)
            context.lineTo(endX, endY)
            context.stroke();
            context.closePath();
          }else{
            context.beginPath();
            context.setLineWidth(3);
            context.setStrokeStyle("#E9E9E9");
            context.moveTo(startX, startY)
            context.lineTo(endX, endY)
            context.stroke();
            context.closePath();
          }
        }else{
          let angel1 = minNum/36*328/angel,angel2 = maxNum/36*328/angel,angel3 = percent/36*328/angel;
          if(i<angel1){
            context.beginPath();
            context.setLineWidth(3);
            context.setStrokeStyle(color[0]);
            context.moveTo(startX, startY)
            context.lineTo(endX, endY)
            context.stroke();
            context.closePath();
          }else if(i>=angel1 && i<=angel2){
            context.beginPath();
            context.setLineWidth(3);
            context.setStrokeStyle(color[1]);
            context.moveTo(startX, startY)
            context.lineTo(endX, endY)
            context.stroke();
            context.closePath();
          }else if(i>angel2 && i<=angel3){
            context.beginPath();
            context.setLineWidth(3);
            context.setStrokeStyle(color[2]);
            context.moveTo(startX, startY)
            context.lineTo(endX, endY)
            context.stroke();
            context.closePath();
          }else{
            context.beginPath();
            context.setLineWidth(3);
            context.setStrokeStyle("#E9E9E9");
            context.moveTo(startX, startY)
            context.lineTo(endX, endY)
            context.stroke();
            context.closePath();
          }
        }
        
    }
    context.restore()
  },
  // 绘制刻度值
  drawScale(){
    let angel = 315/7; //每隔多少度画一个文字
    let outR = circleR + lineWidth - 30  //间条线外边点距离中心点的长度（即外边半径）
    context.save()
    context.translate(centerX-5, centerY+5);  //把中心点移动到
    context.setFillStyle('#999999')
    context.setFontSize(12);
    for(var i = 0;i<8;i++){
      let startX = outR * Math.cos((angel * i+112.5) / 180 * Math.PI)
      let startY = outR * Math.sin((angel * i+112.5) / 180 * Math.PI)
      context.fillText(5*i, startX, startY);
  }
  context.restore()
    
  },
  // 绘制中间百分数文字
  drawText(text,color) {
    //百分比数字
    context.save()
    context.translate(centerX, centerY);
    context.beginPath()
    context.setFontSize(50)
    context.setFillStyle(color)
    context.setTextAlign('center')
    context.setTextBaseline('middle')
    context.fillText(text, 0, 0)
    context.closePath()
    context.restore()
    //单位
    context.save()
    context.translate(centerX, centerY);
    context.beginPath()
    context.setFontSize(17)
    context.setFillStyle(color)
    context.setTextAlign('center')
    context.setTextBaseline('middle')
    context.fillText("mmol/L", 0, 30)
    context.closePath()
    context.restore()
  },
  // 绘制蓝色动态大圆
  drawAnimateCircle(percent,color,minNum,maxNum) {
    
    // percent当前数值 / 最大数值 * 圆的总度数
    let angel = percent/36 * 328

    context.save();
    context.setStrokeStyle(color[0]);
    context.setLineWidth(lineWidth);
    context.beginPath();
    context.translate(centerX, centerY);
    context.rotate(112.5 * Math.PI/180);
    // 绘制半径为大圆半径减去线边框一半,绘制角度从0-angel
    if(percent<minNum){
      context.arc(0, 0, circleR-lineWidth/2, (Math.PI/180)*0, (Math.PI/180)*angel, false);
    }else if(percent>=minNum && percent<=maxNum){
      let minAngel = minNum/36 * 328
      context.arc(0, 0, circleR-lineWidth/2, (Math.PI/180)*0, (Math.PI/180)*minAngel, false);
      context.stroke();
      context.closePath();
      context.restore();
      context.save();
      context.setStrokeStyle(color[1]);
      context.setLineWidth(lineWidth);
      context.beginPath();
      context.translate(centerX, centerY);
      context.rotate(112.5 * Math.PI/180);
      context.arc(0, 0, circleR-lineWidth/2, (Math.PI/180)*minAngel, (Math.PI/180)*angel, false);
    }else{
      let minAngel = minNum/36 * 328
      context.arc(0, 0, circleR-lineWidth/2, (Math.PI/180)*0, (Math.PI/180)*minAngel, false);
      context.stroke();
      context.closePath();
      context.restore();
      context.save();
      context.setStrokeStyle(color[1]);
      context.setLineWidth(lineWidth);
      context.beginPath();
      context.translate(centerX, centerY);
      context.rotate(112.5 * Math.PI/180);
      let midAngel = maxNum/36 * 328
      context.arc(0, 0, circleR-lineWidth/2, (Math.PI/180)*minAngel, (Math.PI/180)*midAngel, false);
      context.stroke();
      context.closePath();
      context.restore();
      context.save();
      context.setStrokeStyle(color[2]);
      context.setLineWidth(lineWidth);
      context.beginPath();
      context.translate(centerX, centerY);
      context.rotate(112.5 * Math.PI/180);
      context.arc(0, 0, circleR-lineWidth/2, (Math.PI/180)*midAngel, (Math.PI/180)*angel, false);
    }
    context.stroke();
    context.closePath();
    context.restore();
  },
  // 绘制动画圆点
  drawAnimateDot(percent) {
    let angel = percent/36 * 328
    // 计算出circleR-lineWidth/2即为中心点到小圆圆心的长度,利用三角函数关系得到小圆圆心坐标点
    let pointX = (circleR-lineWidth/2) * Math.cos((angel+(112.5 - pointR/4))/180 * Math.PI)
    let pointY = (circleR-lineWidth/2) * Math.sin((angel+(112.5 - pointR/4))/180 * Math.PI)

    context.save();
    context.translate(centerX, centerY);
    // context.rotate((165 - pointR/4) * Math.PI/180);
    context.beginPath();
    context.setFillStyle("#ffffff")
    context.setLineWidth(1);
    context.setShadow(0, 0, 5, '#aaa')
    // 再有圆心点和小圆半径绘制小圆所在的位置
    context.arc(pointX, pointY, pointR, 0, 2 * Math.PI)
    context.fill()
    context.closePath();
    context.draw()
    context.restore();
  },

  /**
   * 判断移动的增减 上一坐标a 当前坐标b
   */
  isAddXt(a,b){
    if(a.x>0 && a.y>0){ //第一象限
      if(a.x>=b.x && a.y<=b.y){
        return true;
      }
    }else if(a.x<0 && a.y>0){ //第二象限
      if(a.x>=b.x && a.y>=b.y){
        return true;
      }
    }else if(a.x<0 && a.y<0){ //第三象限
      if(a.x<=b.x && a.y>=b.y){
        return true;
      }
    }else if(a.x>0 && a.y<0){ //第四象限
      if(a.x<=b.x && a.y<=b.y){
        return true;
      }
    }
    return false;
  },

  /**
   * 判断是否为钝角 
   */
  isObtuseAngle(Source){
    var A,R;
    A = Math.atan2(Source.y,Source.x)//atan2自带坐标系识别, 注意X,Y的顺序
    A += defAngle;//旋转
    R = Math.sqrt(Source.x * Source.x + Source.y * Source.y)//半径
// circleR
    let x = Math.cos(A)*R,y = Math.sin(A)*R;
    console.log("进来的坐标轴为",Source)
    console.log("转化后的坐标轴为",x,y)
    if(x>=0){
      return true;
    }else{
      return false;
    }
  },

  /**
   * 计算两坐标之间的角度 对应的血糖值
   */
  calcAngle(second){
    const cen = {x:0,y:0};
    var pa_x = firstIndex.x - cen.x;
    var pa_y = firstIndex.y - cen.y;
    var pb_x = second.x - cen.x;
    var pb_y = second.y - cen.y;
    var v1 = (pa_x * pb_x) + (pa_y * pb_y);
    var pa_val = Math.sqrt(pa_x * pa_x + pa_y * pa_y);
    var pb_val = Math.sqrt(pb_x * pb_x + pb_y * pb_y);
    var cosAgl = v1 / (pa_val * pb_val);
    var angle = Math.acos(cosAgl) * 180 / Math.PI;

    if(firstIndex.x*second.y - second.x*firstIndex.y<0){  //this.isObtuseAngle(second)
      angle = 360 - angle;
    }

    let currentElec = parseFloat(angle/328 * 36).toFixed(1);
    if(currentElec>36) return;
    if(parseFloat(currentElec) > 34.9) currentElec = 35;
    else if(parseFloat(currentElec) < 0.1) currentElec = 0;

    //计算当前180°对应的血糖值
    
    
    this.setData({
      currentElec: currentElec
    })
    this.startAnimate()
  },

  /**
   * canvas点击滑动效果实现 
   */
  touchstart(e){

//     let angel = this.data.currentElec/36 * 220;
    // 计算出circleR-lineWidth/2即为中心点到小圆圆心的长度,利用三角函数关系得到小圆圆心坐标点
//     let pointX = (circleR-lineWidth/2) * Math.cos((angel+(165 - pointR/4))/180 * Math.PI)
//     let pointY = (circleR-lineWidth/2) * Math.sin((angel+(165 - pointR/4))/180 * Math.PI)
    //console.log(pointX,pointY)
    top = e.target.offsetTop + (this.data.canvasWidth/2);
    left = e.target.offsetLeft + (this.data.canvasWidth/2);
    //当前点击坐标
    // console.log("第一次点击坐标",e.touches[0].pageX-left,e.touches[0].pageY-top)
    startIndex.x=e.touches[0].pageX-left;
    startIndex.y=e.touches[0].pageY-top;

    this.calcAngle(startIndex);
    //判断第一次点击的坐标是否距离圆点接近
//     if(Math.abs(Math.abs(startIndex.x)-Math.abs(pointX)) < 25 && Math.abs(Math.abs(startIndex.y)-Math.abs(pointY) < 25)){
//       canMove = true
//     }else{ canMove = false}


  },

  touchmove(e){
    let a = {}; //存放当前鼠标坐标
    a.x = e.touches[0].pageX-left;
    a.y = e.touches[0].pageY-top;
    this.calcAngle(a);
  },
  touchend(){
    canMove = false;
  },

  /**
   * 默认两位数
   */
  getDbNum(e){
    return parseInt(e)<10?("0"+e):e.toString();
  },
  /**
   * 获取周
   */
  getWeek(num){
    switch(num.toString()){
      case '1': return '周一';
      case '2': return '周二';
      case '3': return '周三';
      case '4': return '周四';
      case '5': return '周五';
      case '6': return '周六';
      case '0': return '周日';
    }
  },

  /**
   * 点击下拉获取当前模块数据
   */
  selOpenModel(e){
    const name = e.currentTarget.dataset.name;
    let isOpen = this.data[name];
    this.setData({
      [`${name}`]:!isOpen
    })
  }
})